import fetch from "../../utils/fetch";
const globalData = getApp().globalData;
const {
  gotoLogin
} = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUserId: 0, //记录当前用户id，用于判断文章是否可以删除
    placeholderText: '评论', //发送输入框提示信息
    commentContent: '', //输入的评论内容
    postDetail: {}, //文章详情
    comments: [], //评论
    //回复评论的父级评论的位置
    parentIdx: -1,
    //回复的评论
    replyComment: {},
  },

  size: 10, //一次获取十条评论
  page: 1, //第几次获取评论
  count: 0, //评论条数
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.size = 10;
    this.page = 1;
    this.setData({
      currentUserId: globalData.userInfo.id
    })
    wx.showLoading({
      title: '数据加载中',
    })
    //文章id
    const postId = options.postId
    //获取文章详情
    this.getArticleDetail(postId);
  },
  //获取文章详情
  getArticleDetail(postId) {
    var that = this;
    //获取文章详情
    fetch('/post/detail', {
      postId,
      userId: globalData.userInfo.id ? globalData.userInfo.id : -1,
      size: that.size,
      page: that.page
    }).then(res => {
      wx.hideLoading();
      this.count = res.data.count;
      this.setData({
        postDetail: res.data.post,
        comments: res.data.comments
      });
    }).catch(err => {
      this.getArticleDetail(postId);
    })
  },
  previewImg(e){
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      urls: this.data.postDetail.imgs,
      current:this.data.postDetail.imgs[index]
    });
  },
  //删除文章
  deletePost() {
    const postId = this.data.postDetail.id;
    wx.showModal({
      title: '删除文章',
      content: '确定删除文章吗？'
    }).then(res => {
      if (res.confirm) {
        wx.showLoading({
          title: '文章删除中',
        });
        fetch('/post/delete', {
          postId: postId,
          userId: globalData.userInfo.id,
        }).then(res => {
          wx.hideLoading();
          globalData.userInfo.score -= 1;
          wx.setStorageSync('userInfo', globalData.userInfo)
          wx.showToast({
            title: '删除成功',
          });
          setTimeout(() => {
            wx.navigateBack()
          }, 1000);
        }).catch(err => {
          wx.hideLoading();
          wx.showToast({
            title: '删除失败，请重新尝试',
            icon: 'none',
            duration: 1000
          });
        })
      }
    })
  },

  //获取输入评论内容
  getValue: function (e) {
    this.setData({
      commentContent: e.detail.value,
    });
  },
  //发送评论
  sendComment(){
    if(!globalData.isLogin){
      gotoLogin();
      return ;
    }
    const commentContent = this.data.commentContent;
     //动态内容不能为空
     if(commentContent){
      wx.showLoading({
        title: '发送中',
        mask:true
      })
       //检测动态内容是否安全
      fetch('/util/checkText',{
        content:commentContent,
        openid:globalData.userInfo.openid,
        scene:2
      },'post').then(res=>{
        if(res.data.isLegal){
          //添加评论
          this.addComment(commentContent); 
        }else{
          wx.showToast({
            title: '文字不安全',
          })
        }
      }).catch(err=>{
        console.log(err);
        // this.sendComment();
      }) 
    }
    else{
      wx.showToast({
        title: '评论内容不能为空!',
        duration: 1000,
        icon: 'none',
      })
    }
  },

  //添加新评论
  addComment(commentContent){
    let postUser = this.data.postDetail.user.id;
    let parentCommentId,replyCommentId,flag,replyerId,replyerName,postId,userId;
    flag = this.data.postDetail.user.id == globalData.userInfo.id ? true : false;
    postId = this.data.postDetail.id;
    userId = globalData.userInfo.id;
    const parentIdx = this.data.parentIdx;
    if(parentIdx > -1){
      const replyComment = this.data.replyComment;
      parentCommentId = this.data.comments[parentIdx].id;
      replyCommentId = replyComment.id;
      replyerId = replyComment.user.id;
      replyerName = replyComment.user.username;
    }else{
      parentCommentId = null;
      replyCommentId = null;
      replyerId = null;
      replyerName = null;
    }
    //新增评论
    fetch('/comment/add',{
      content:commentContent,
      parentCommentId,replyCommentId,flag,replyerId,replyerName,postId,userId,postUser
    },'post').then(res=>{
      globalData.userInfo.score +=1;
      wx.setStorageSync('userInfo', globalData.userInfo);
      this.setData({
        commentContent: '',
        placeholderText:'评论',
        parentIdx:-1,
        replyComment:{}
      });
      this.page = 1;
      this.getArticleDetail(this.data.postDetail.id);
  
    }).catch(err=>{
      this.addComment(commentContent)
    })
  },
  deleteComment(e){
    const index = e.currentTarget.dataset.index;
    const childIdx = e.currentTarget.dataset.childIdx;
    const postId = this.data.postDetail.id;
    let comment = {};
    // 如果是楼中楼
    if(childIdx>-1){
      comment = this.data.comments[index].childrenComments[childIdx];
    }else{
      comment = this.data.comments[index];
    }
    const commentId = comment.id;
    const parentCommentId = comment.parentCommentId;
    //删除评论
    wx.showLoading({
      title: '评论删除中',
      mask:true
    });
    fetch('/comment/delete',{
      commentId,
      parentCommentId,
      postId,
      userId: globalData.userInfo.id
    }).then(res=>{
      globalData.userInfo.score -=1;
      wx.setStorageSync('userInfo', globalData.userInfo)
      this.page = 1;
      this.count = 0;
      
      this.getArticleDetail(this.data.postDetail.id);
    }).catch(err=>{
      wx.showToast({
        title: '评论删除失败，请重新尝试',
        icon: 'none',
        duration: 1000,
        mask:true
      })
    })
  },
  changeReply(e){
    const index = e.currentTarget.dataset.index;
    const childIdx = e.currentTarget.dataset.childIdx;
    let replyComment;
    let placeholderText;
    if(childIdx>-1){
      replyComment = this.data.comments[index].childrenComments[childIdx];
      placeholderText = '回复' + replyComment.user.username;
    }else{
      replyComment = this.data.comments[index];
      placeholderText = '回复' + replyComment.user.username
    }
    this.setData({
      parentIdx:index,
      replyComment,
      placeholderText
    })
  },
  //点击空白返回评论
  comment(){
    this.setData({
      placeholderText:'评论',
      parentIdx:-1,
      replyComment:{}
    })
  },
  gotoCenter(e){
    const userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `../personalCenter/personalCenter?userId=${userId}`,
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.page * this.size >= this.count ){
      return ;
    }
    wx.showLoading({
      title: '加载更多评论',
    })
    this.page = this.page + 1;
    fetch('/comment/getList',{
      postId:this.data.postDetail.id,
      page:this.page,
      size:this.size
    }).then(res=>{
      this.count = res.data.count;
      let comments = this.data.comments;
      res.data.comments.forEach(item=>{
        comments.push(item);
      });
      this.setData({
        comments
      });
      wx.hideLoading();
    })
  },
  goback(){
    wx.switchTab({
      url: '/pages/community/community',
    })
  }
})